import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_integer("is_train", 1, "是训练还是预测")

def cifar():
    mnist = input_data.read_data_sets('./data/mnist/input_data', one_hot=True)
    print(mnist.train.next_batch(10))
    # 1. 创建数据的占位符, x--> [None, 784], y_true [None, 10]
    with tf.variable_scope('data'):
        x = tf.placeholder(tf.float32, [None, 784])
        y_true = tf.placeholder(tf.int8, [None, 10])
    # 2. 建立一个全连接的神经网络 w [785, 10], b: [10]
    with tf.variable_scope('fc_model'):
        weight = tf.Variable(tf.random_normal(shape=[784, 10], mean=0.0, stddev=1.0), name='w')
        bias = tf.Variable(tf.constant(value=0.0, shape=[10]))
        y_predict = tf.matmul(x, weight) + bias
    # 3. 求出所有样本的损失, 然后求平均值
    with tf.variable_scope('soft_cross'):
        loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_true, logits=y_predict))
    # 4. 梯度下降优化损失
    with tf.variable_scope('optimizer'):
        train_op = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(loss)
    # 5. 计算准确率
    with tf.variable_scope('acc'):
        equal_list = tf.equal(tf.argmax(y_true, 1), tf.argmax(y_predict, 1))
        accuracy = tf.reduce_mean(tf.cast(equal_list, tf.float32))
    # 收集变量 单个数字值收集
    tf.summary.scalar("losses", loss)
    tf.summary.scalar("acc", accuracy)
    # 高纬度变量收集
    tf.summary.histogram("weightes", weight)
    tf.summary.histogram("biases", bias)
    # 定义一个初始化变量的op
    init_op = tf.global_variables_initializer()
    # 定义一个合并变量de op
    merged = tf.summary.merge_all()
    saver = tf.train.Saver()
    with tf.Session() as sess:
        sess.run(init_op)
        file_writer = tf.summary.FileWriter('./tmp/summary/test/', graph=sess.graph)
        if FLAGS.is_train == 1:
            for i in range(5000):
                mnist_x, mnist_y = mnist.train.next_batch(50)
                sess.run(train_op, feed_dict={x:mnist_x, y_true:mnist_y})
                summary = sess.run(merged, feed_dict={x:mnist_x, y_true:mnist_y})
                file_writer.add_summary(summary, i)
                print("训练第%d步,准确率为:%f" % (i, sess.run(accuracy, feed_dict={x: mnist_x, y_true: mnist_y})))
            saver.save(sess, './tmp/xingyeah_model')
        else:
            saver.restore(sess, './tmp/xingyeah_model')
            for i in range(100):
                x_test, y_test = mnist.test.next_batch(50)
                print("第i张图片%d：目标值：%d，预测结果: %d" % (
                    i,
                    tf.argmax(y_test, 1).eval()[0],
                    tf.argmax(sess.run(y_predict, feed_dict={x: x_test, y_true: y_test}), 1).eval()[0]
                ))
if __name__ == '__main__':
    cifar()